package org.ph.share.lock.test.thread2;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 执行三个线程顺序输出abcabc
 * Use ReentrantLock
 *
 * @author Hush.
 * @since 2023/5/18 12:53
 */
@Slf4j
public class Thread17 {
    public static void main(String[] args) throws InterruptedException {

        AwaitAndSignal awaitAndSignal = new AwaitAndSignal(2);
        Thread thread1 = new Thread(() -> awaitAndSignal.print(1, "a", 2), "t1");
        Thread thread2 = new Thread(() -> awaitAndSignal.print(2, "b", 3), "t2");
        Thread thread3 = new Thread(() -> awaitAndSignal.print(3, "c", 1), "t3");
        thread1.start();
        thread2.start();
        thread3.start();

    }
}

@Slf4j
class AwaitAndSignal {
    ReentrantLock lock = new ReentrantLock();
    Condition FREE_WAIT = lock.newCondition();
    /**
     * 标记
     */
    private int flag;
    /**
     * 循环次数
     */
    private final int cycles;

    public AwaitAndSignal(int cycles) {
        this.cycles = cycles;
        this.flag = 1;
    }

    /**
     * 打印
     *
     * @param waitFlag 等待标记
     * @param mess     消息
     * @param nextFlag 下个标记
     */
    public void print(int waitFlag, String mess, int nextFlag) {
        for (int i = 0; i < cycles; i++) {
            lock.lock();
            try {
                // 当前flag不与线程传来的参数一致，进入等待
                while (this.flag != waitFlag) {
                    try {
                        FREE_WAIT.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                this.flag = nextFlag;
                log.info("mess:{}", mess);
                FREE_WAIT.signalAll();
            } finally {
                lock.unlock();

            }
        }
    }
}